package com.share.example.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.common.common.Page;
import com.share.common.utils.IpUtil;
import com.share.example.stock.mapper.ScheduleLogMapper;
import com.share.example.stock.model.db.ScheduleLog;
import com.share.example.stock.model.db.User;
import com.share.example.stock.model.rsp.ScheduleLogPageReq;
import com.share.example.stock.service.IScheduleLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 定时任务日志记录表  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-06-05
 */
@Service
public class ScheduleLogServiceImpl extends ServiceImpl<ScheduleLogMapper, ScheduleLog> implements IScheduleLogService {
    @Resource
    private ScheduleLogMapper scheduleLogMapper;

    @Override
    public ScheduleLog insertLog(String jobCode) {
        ScheduleLog taskLog = new ScheduleLog();
        taskLog.setJobCode(jobCode);
        taskLog.setExeIp(IpUtil.getIp());
        taskLog.setStatus("0");
        taskLog.setBeginTime(new Date());
        taskLog.setCreateTime(new Date());
        int insert = scheduleLogMapper.insert(taskLog);
        if (insert > 0) {
            return taskLog;
        } else {
            return null;
        }
    }

    @Override
    public int updateLogById(ScheduleLog taskLog) {
        taskLog.setEndTime(new Date());
        return scheduleLogMapper.updateById(taskLog);
    }

    @Override
    public Page pageList(ScheduleLogPageReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<ScheduleLog> queryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(req.getRemark())) {
            queryWrapper.like(ScheduleLog::getRemark, req.getRemark());
        }
        if (StringUtils.isNotBlank(req.getExpMsg())) {
            queryWrapper.like(ScheduleLog::getExpMsg, req.getExpMsg());
        }
        if (StringUtils.isNotBlank(req.getExeIp())) {
            queryWrapper.like(ScheduleLog::getExeIp, req.getExeIp());
        }
        if (StringUtils.isNotBlank(req.getJobCode())) {
            queryWrapper.like(ScheduleLog::getJobCode, req.getJobCode());
        }
        queryWrapper.orderByDesc(ScheduleLog::getId);
        List<ScheduleLog> list = scheduleLogMapper.selectList(queryWrapper);
        return new Page<>(list, new PageInfo<>(list).getTotal(), req);
    }
}
